import subprocess

"""def execute_command(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
    return process"""

"""def run_command(command, ws, id, list, id_list):

    command = command.strip()
    if id not in list:
        id_list[id] = './'

        # 如果是 cd 命令，则更新当前目录
        if command.startswith('cd '):
            directory = command.split(' ', 1)[-1].strip()  # 获取 cd 命令后面的目录
            try:
                # 尝试切换目录
                #subprocess.Popen(f'cd "{directory}"', shell=True).communicate()

                id_list[id] = id_list[id] + directory
                print(id_list[id])
                ws.emit("response", {"value": "[shell](" + id_list[id] + ") # "}, namespace="/Shell")
                list[id] = execute_command(f'cd "{directory}" && {command}')
                return list, id_list
            except Exception as e:
                print(f"无法切换到目录 '{id_list[id]}'：{e}")
                ws.emit("response", {"value": "[shell] # "}, namespace="/Shell")
                return list, id_list
        current_directory = id_list[id]
        # 在当前目录执行命令
        list[id] = execute_command(f'cd "{current_directory}" && {command}')
        # 实时打印命令的输出
        while True:
            output = list[id].stdout.readline()  # 读取输出流
            if output == '' and list[id].poll() is not None:  # 没有新的输出并且进程已经结束
                list[id].stdout.close()
                ws.emit("response", {"value": f"[shell]({id_list[id]}) # "}, namespace="/Shell")

            if output:
                ws.emit("response", {"value": output.strip()}, namespace="/Shell")
        return list, id_list
    else:
        print(id_list[id])
        current_directory = id_list[id]
        print("存在该进程")

    # 如果是 cd 命令，则更新当前目录
    if command.startswith('cd '):
        directory = command.split(' ', 1)[-1].strip()  # 获取 cd 命令后面的目录
        try:
            # 尝试切换目录
            #subprocess.Popen(f'cd "{directory}"', shell=True).communicate()
            current_directory = directory
            id_list[id] = id_list[id] + directory
            print(id_list[id])
            ws.emit("response", {"value": "[shell](" + id_list[id] + ") # "}, namespace="/Shell")
            return list, id_list
        except Exception as e:
            print(f"无法切换到目录 '{id_list[id]}'：{e}")
            ws.emit("response", {"value": "[shell] # "}, namespace="/Shell")
            return list, id_list

    # 在当前目录执行命令
    list[id] = execute_command(f'cd "{current_directory}" && {command}')
    #list[id].stdin.write(command)  # 将用户输入写入子进程的标准输入
    #list[id].stdin.flush()  # 刷新标准输入，确保数据被发送
    # 实时打印命令的输出
    while True:
        output = list[id].stdout.readline()  # 读取输出流
        if list[id].poll() is not None:  # 没有新的输出并且进程已经结束
            list[id].stdout.close()
            ws.emit("response", {"value": f"[shell]({id_list[id]}) # "}, namespace="/Shell")
        if output:
            ws.emit("response", {"value": output.strip()}, namespace="/Shell")
    return list, id_list"""

import os
import shlex
import subprocess
import sys
import time

# 初始化当前工作目录
cwd = os.getcwd()


def run_command(command, ws, id, list, id_list):
    # 显示命令提示符
    if id not in list:
        cwd = os.getcwd()
        id_list[id] = cwd

    else:
        print(id_list[id])
        current_directory = id_list[id]
        print("存在该进程")
        cwd = current_directory

    prompt = f"{cwd}># "

    parts = shlex.split(command)
    if len(parts) == 0:
        ws.emit("response", {"value": prompt}, namespace="/Shell")
        return list, id_list
    elif parts[0].lower() == "exit":
        pass


    # 处理 cd 命令
    if parts[0].lower() == "cd":
        try:
            # 切换目录
            if len(parts) > 1:
                os.chdir(parts[1])
            else:
                os.chdir(os.path.expanduser("~"))
            cwd = os.getcwd()
            id_list[id] = cwd
            ws.emit("response", {"value": f"{cwd}># "}, namespace="/Shell")
            return list, id_list
        except Exception as e:
            print(f"无法切换目录: {e}")
            ws.emit("response", {"value": f"{cwd}># "}, namespace="/Shell")
            return list, id_list
    else:
        try:
            # 启动新的子进程，并执行命令
            list[id] = subprocess.Popen(parts, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                        universal_newlines=True, cwd=cwd)

            # 循环读取输出并实时输出
            for line in iter(list[id].stdout.readline, ''):
                print(line.rstrip())
                ws.emit("response", {"value": line.rstrip()}, namespace="/Shell")


            # 等待子进程结束
            list[id].wait()


            # 打印错误信息
            errors = list[id].stderr.read()
            print(errors.strip())

            # 更新当前工作目录
            cwd = os.getcwd()
            id_list[id] = cwd
            ws.emit("response", {"value": f"{cwd}># "}, namespace="/Shell")
            return list, id_list
        except FileNotFoundError:
            print(f"找不到命令: {command}")
            ws.emit("response", {"value": f"找不到命令: {command}"}, namespace="/Shell")
            return list, id_list
